package com.feather.tenia.oracle.fetcher;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import oracle.jdbc.OracleTypes;
import oracle.sql.BLOB;

import com.feather.common.data.Column;
import com.feather.common.data.DataColumn;
import com.feather.common.data.DataItem;
import com.feather.common.db.DbFetcher;
import com.feather.common.util.FileUtil;
import com.feather.tenia.adapter.data.Bytearray_DataColumn;

/**
 * @author flogyin
 */
public class BLOB_Fetcher implements DbFetcher {
	@Override
	public String getDbType() {
		return "blob";
	}

	@Override
	public int getSqlType() {
		return OracleTypes.BLOB;
	}

	@Override
	public DataColumn fetch(ResultSet rs, Column column) throws SQLException {
		BLOB blob = (BLOB) rs.getBlob(column.getOrdinal());
		byte[] data = null;
		if (blob != null && !blob.isEmptyLob()) {
			try {
				data = FileUtil.read(blob.getBinaryStream(), true);
			} catch (IOException ex) {
				throw new SQLException(ex.toString());
			}
		}
		Bytearray_DataColumn dataColumn = new Bytearray_DataColumn(column);
		dataColumn.setBytes(data);
		return dataColumn;
	}

	@Override
	public DataItem fetch(CallableStatement statement, Column column) throws SQLException {
		BLOB blob = (BLOB) statement.getBlob(column.getOrdinal());
		byte[] data = null;
		if (blob != null && !blob.isEmptyLob()) {
			try {
				data = FileUtil.read(blob.getBinaryStream(), true);
			} catch (IOException ex) {
				throw new SQLException(ex.toString());
			}
		}
		Bytearray_DataColumn dataColumn = new Bytearray_DataColumn(column);
		dataColumn.setBytes(data);
		return dataColumn;
	}
}
